package com.shiyue.cqe.dao.impl;

import java.lang.reflect.ParameterizedType;
import java.util.List;
import java.util.Map;

import org.hibernate.SQLQuery;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.transform.Transformers;

import com.shiyue.cqe.dao.Repository;

public class HibernateGenericDAO<T> implements Repository<T> {
	protected Class<T> persistClass;
	private SessionFactory sessionFactory;
	
	@SuppressWarnings("unchecked")
	public HibernateGenericDAO(SessionFactory sessionFactory) {
		this.persistClass = (Class<T>)((ParameterizedType)this.getClass()
			.getGenericSuperclass()).getActualTypeArguments()[0];
		this.sessionFactory = sessionFactory;
	}

	/**
	 * Returns the session for the current executing context
	 * @return the session
	 */
	protected Session session() {
		return this.sessionFactory.getCurrentSession();
	}

	/**
	 *
	 */
	public void remove(T entity) {
		this.session().delete(entity);
	}

	/**
	 */
	@SuppressWarnings("unchecked")
	public T get(int id) {
		return (T)this.session().get(this.persistClass, id);
	}

	/**
	 */
	public void add(T entity) {
		this.session().save(entity);
	}

	public void update(T entity) {
		this.session().update(entity);
	}
	
	public int excuteSQL(String sql,Object ... objs){
		SQLQuery sqlQuery = this.session().createSQLQuery(sql);
		int parameterIndex = 0;
		for(Object obj : objs){
			sqlQuery.setParameter(parameterIndex, obj);
			parameterIndex++;
		}
		return sqlQuery.executeUpdate();
	}
	
	@SuppressWarnings("unchecked")
	public List<Map> querySQL(String sql,Object ... objs){
		SQLQuery sqlQuery = this.session().createSQLQuery(sql);
		int parameterIndex = 0;
		for(Object obj : objs){
			sqlQuery.setParameter(parameterIndex, obj);
			parameterIndex++;
		}
		sqlQuery.setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
		return sqlQuery.list();
	}

}
